package com.apes.scm.masterdata.party.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderDao;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 功能：接入商
 *
 * @author LinWZ
 * @create 2019-12-09 16:35
 */
@Service("accessProviderService")
public class AccessProviderService extends DomainService {
    private static final String ROLE_TYPE = "Customer";

    @Autowired
    AccessProviderRepository accessProviderRepository;
    @Autowired
    AccessProviderDao accessProviderDao;
    @Autowired
    PartyRoleRepository partyRoleRepository;

    public AccessProvider save(SimpleRequest request) {
        AccessProvider accessProvider = request.getO(AccessProvider.class);
        // 添加中间表信息
        List<JSONObject> companyList = accessProvider.getCompanyLits();
        if (companyList != null) {
            List<PartyRole> companys = new ArrayList<>();
            companyList.stream().forEach(
                    (postJ) -> {
                        PartyRole company = partyRoleRepository.findOne(postJ.getString("id"));
                        companys.add(company);
                    }
            );
            accessProvider.setCompanys(companys);
        }
        accessProvider = accessProviderRepository.saveAndFlush(accessProvider);
        updateCompanyAccessProvider(accessProvider); // 更新公司接入商
//        checkSettlementCenter(accessProvider);
        return accessProvider;
    }

    public AccessProvider update(SimpleRequest request) {
        AccessProvider accessProvider = request.getO(AccessProvider.class);
        // 添加中间表信息
        List<JSONObject> companyList = accessProvider.getCompanyLits();
        if (companyList != null) {
            List<PartyRole> companys = new ArrayList<>();
            companyList.stream().forEach(
                    (postJ) -> {
                        PartyRole company = partyRoleRepository.findOne(postJ.getString("id"));
                        companys.add(company);
                    }
            );
            accessProvider.setCompanys(companys);
        }
        updateCompanyAccessProvider(accessProvider); // 更新公司接入商
        AccessProvider result = accessProviderRepository.saveAndFlush(accessProvider);
//        checkSettlementCenter(result);
        result.setCompanyLits(accessProvider.getCompanyLits());
        return result;
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        AccessProvider accessProvider = accessProviderRepository.findOne(id);
        if (accessProvider == null) throw new RuntimeException("接入商【" + id + "】在系统中不存在。");
        accessProvider.setCompanys(new ArrayList<>());
        accessProviderRepository.delete(accessProvider);
        return "删除成功！";
    }


    public void checkSettlementCenter(AccessProvider accessProvider) {
        if (accessProvider.getCompanys() != null) {
            Map<Area, List<PartyRole>> areaListMap = accessProvider.getCompanys().stream().filter(company -> company.getParty().isSettlementCenter()).collect(Collectors.groupingBy(e -> e.getParty().getCorporate().getRegCity()));
            areaListMap.forEach((area, partyRoles) -> {
                if (partyRoles.size() > 1) {
                    throw new RuntimeException("同一接入商在同一城市只能有一个公司是【区域结算中心】");
                }
            });
        }

    }


    /*
     * 定接入商 数据格式化给前端
     * */
    public Page<AccessProvider> findAllForUi(SimpleRequest request) {
        Page<AccessProvider> accessProviderPage = request.getO(Page.class);
        accessProviderPage.getContent().stream().forEach(
                (accessProvider) -> {
                    List<PartyRole> companys = accessProvider.getCompanys();
                    if (companys != null) {
                        List companyLits = new ArrayList();
                        companys.stream().forEach(
                                (company) -> {
                                    JSONObject postJo = new JSONObject();
                                    postJo.put("id", company.getId());
                                    postJo.put("name", company.getName());
                                    companyLits.add(postJo);
                                }
                        );
                        accessProvider.setCompanyLits(companyLits);
                    }
                }
        );
        return accessProviderPage;
    }

    public JSONObject accordingCompanyAccessProvider(SimpleRequest simpleRequest) {
        AccessProvider accessProvider = accessProviderRepository.findByCompany(simpleRequest.get("companyId"));
        if (accessProvider == null) return null;
        JSONObject returnData = new JSONObject();
        returnData.put("vendorCode", accessProvider.getId());
        return returnData;
    }

    /***
     * 补全对应公司的接入商，先清空再写入
     */
    private void updateCompanyAccessProvider(AccessProvider accessProvider){

        List<PartyRole> companies = partyRoleRepository.findAll(
                JpaDsl.toCriteriaByEq(
                        "accessProvider.id", accessProvider.getId()
                )
        );

        // 先删除
        companies.stream().forEach(company -> {
            company.setAccessProvider(null);
            partyRoleRepository.saveAndFlush(company);
        });

        if (accessProvider.getCompanys() == null) return;
        // 再写入
        accessProvider.getCompanys().stream().forEach(company -> {
            company.setAccessProvider(accessProvider);
            partyRoleRepository.saveAndFlush(company);
        });
    }

}
